package r25;

import java.io.InputStream;

import org.slf4j.Logger;

import r25.engine.IGameService;
import r25.settings.GameConfigResource;
import r25.tools.LoggerHelper;

public class ServiceFactory {
	private static final Logger logger = LoggerHelper.getLogger();
	private static ServiceFactory instance;
	private IGameService gs;

	public static synchronized ServiceFactory getInstance() throws Exception {
		// @formatter:off
		if (instance == null)
			instance = new ServiceFactory();
		// @formatter:on
		return instance;
	}

	public void configure(String file) throws Exception {
		synchronized (this) {
			GameConfigResource.loadResource(file);
			gs = null;
		}
	}

	public void configure(InputStream in) throws Exception {
		synchronized (this) {
			GameConfigResource.loadResource(in);
			gs = null;
		}
	}

	public IGameService getGameService() throws Exception {
		if (gs == null) {
			String library = GameConfigResource.getParamString("library");
			if (library == null) {
				logger.debug("", GameConfigResource.getMap());
				return null;
			}

			logger.debug("ISWService class: {}", library);
			gs = (IGameService) Class.forName(library).newInstance();
			gs.configure(GameConfigResource.getMap());
		}
		return gs;
	}

	/**
	 * <p>
	 * releaseAuditService.
	 * </p>
	 * 
	 * @throws java.lang.Exception
	 *             if any.
	 */
	public void releaseSWService() throws Exception {
		synchronized (this) {
			logger.debug("Releasing ISWService");
			if (gs != null) {
				gs.release();
				gs = null;
			}
		}
	}
}
